import React from 'react';
import { ListView, Icon, NavBar, Toast } from 'antd-mobile';
import Router from 'next/router';
import SingleItem from '../../src/components/singleItem';
import { getRequest } from '../../tools/requests';
import HeadC from '../../src/components/layout/head';
import FooterC from '../../src/components/layout/footer';
// import './index.css';


const NUM_ROWS = 20;
let pageIndex = 0;

function genData(pIndex = 0) {
  const dataBlob = {};
  for (let i = 0; i < NUM_ROWS; i++) {
    const ii = (pIndex * NUM_ROWS) + i;
    dataBlob[`${ii}`] = `row - ${ii}`;
  }
  return dataBlob;
}


export default class CategoriesNoNav extends React.Component {
  static async getInitialProps({query}) {
    return {
      title: 'coupon',
			description: '',
			links: '',
      ogImage: '',
      cateName: query.cateName
    }
  }
  constructor(props) {
    super(props);
    const dataSource = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2,
    });

    this.state = {
      dataSource,
      isLoading: true,
      height: 0,
      goodsLists: [],
      noMore: false
    }
  }
  componentDidMount() {
    const docHeight = document.documentElement.clientHeight;
    this.getGoodsLists(1).then(() => {
      this.setState({
        dataSource: this.state.dataSource.cloneWithRows(this.rData),
        isLoading: false,
        height: docHeight - 80,
        goodsLists: this.state.goodsLists
      });
    });
  }

  async onEndReached(event) {
		if (this.state.noMore) {
      return false;
    }
    this.setState({ isLoading: true });
    let pageAdd = ++pageIndex;
		pageAdd == 1 && (pageAdd = 2);
    const result = await getRequest('goods_list/', {page: pageAdd, page_size: NUM_ROWS, topcate: this.props.cateName, subcate: this.state.currentClass});
    if (result.data) {
      this.rData = { ...this.rData, ...genData(pageAdd) };
      this.setState({
        goodsLists: result.data,
        dataSource: this.state.dataSource.cloneWithRows(this.rData),
        isLoading: false,
      });
    }else {
      this.setState({
        isLoading: false,
        goodsLists: [],
        noMore: true
      })
      Toast.fail(result.msg, 1);
    }
  }

  // 异步获取数据
  async getGoodsLists(pageIndex) {
    const result = await getRequest('goods_list/', {page: pageIndex, page_size: NUM_ROWS, topcate: this.props.cateName, subcate: this.state.currentClass})
    if (result.data) {
      this.rData = genData();
      this.setState({
        dataSource: this.state.dataSource.cloneWithRows(this.rData),
        isLoading: false,
        goodsLists: result.data,
      });
    }else {
      this.setState({
        isLoading: false,
        goodsLists: [],
        noMore: true
      })
      Toast.fail(result.msg, 1);
    }
  }
  render() {
    const { title, description, links, ogImage, cateName } = this.props;
    const row = (rowData, sectionID, rowID) => {
      let indexID = rowID > 20 ? rowID % 20 === 0 ? 19 : (rowID % 20) - 1 : rowID;
      let objItem = this.state.goodsLists[indexID] ? (
        <SingleItem key={rowID} item={this.state.goodsLists[indexID]}></SingleItem>
      ) : null;
      return objItem
    };
    return (
      <div>
        <HeadC 
					title={title} 
					description={description}
					links={links}
					ogImage={ogImage}
				></HeadC>
        <NavBar
          mode="light"
          icon={<Icon type="left" />}
          onLeftClick={() => Router.back()}
          style={{color: '#fa4d47', zIndex: 999}}
          className="detail-nav-block"
        >
          { cateName }
        </NavBar>
        <ListView
          ref={el => this.lv = el}
          dataSource={this.state.dataSource}
          renderFooter={() => (
            <div style={{ padding: 10, textAlign: 'center' }}>
              {this.state.isLoading ? <Icon type="loading" /> : '已经到最底部了....'}
            </div>
          )}
          style={{
            height: this.state.height,
            overflow: 'auto',
            marginTop: '46px'
          }}
          renderRow={row}
          pageSize={NUM_ROWS}
          onScroll={() => { console.log('scroll'); }}
          scrollRenderAheadDistance={500}
          onEndReached={this.onEndReached.bind(this)}
          onEndReachedThreshold={10}
        />
        <FooterC src="../../static/images/police.png" />
      </div>
    )
  }
}